<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of MT
 *
 * @author Administrator
 */

namespace frontend\library;
define('CURRENT_TIME', time());
define('CURRENT_TIME_MICRO', microtime());
define('CURRENT_PLATFORM', @ MT::judgeUserAgent());
define('CURRENT_VERSION', MT::judgeUserVersion());

class MT {

    //put your code here
    public static $data = array();

    public static function setData($k, $v, $name_space = 'system') {
        self::$data[$name_space][$k] = $v;
    }

    public static function getData($k, $name_space = 'system') {

        return isset(self::$data[$name_space][$k]) ? self::$data[$name_space][$k] : null;
    }

    public static function getAllData($name_space = 'system') {
        return isset(self::$data[$name_space]) ? self::$data[$name_space] : array();
    }

    /**
     * 获取当前时间戳
     *
     * @return int
     */
    static public function getTime($refresh=false) {
        return $refresh?time():CURRENT_TIME;
    }

    static public function getUserDir($uid) {
        $uid = sprintf("%09d", $uid);
        return substr($uid, 0, 3) . '/' . substr($uid, 3, 2) . '/' . substr($uid, 5, 2);
    }

    static public function getDateDir($id) {
        $dir = '';
        $dir .= date('Ym');
        $dir .= '/' . date('d');
        if ($id)
            $dir .= '/' . $id;
        return $dir;
    }

    /**
     * 获取配置文件zip包路径
     * @param string $path 配置文件路径
     * @return string
     */
    public static function getZipPath($path) {
        $dir_path = dirname($path);
        $file = substr($path, strrpos($path, '/') + 1);
        $file_name = explode('.', $file);
        $zip_path = '';
        if (is_file($dir_path . '/' . $file_name[0] . '.zip')) {
            $zip_path = $dir_path . '/' . $file_name[0] . '.zip';
        } elseif (strpos($file_name[0], '_')) {
            $file_name_2 = explode('_', $file_name[0]);
            if (is_file($dir_path . '/' . $file_name_2[0] . '.zip')) {
                $zip_path = $dir_path . '/' . $file_name_2[0] . '.zip';
            }
        }
        return $zip_path;
    }

    /**
     * 单个文件写入zip包
     * 
     * @param string $file 待写入的文件
     * @param string $filename 生成的ZIP文件名
     */
    public static function createZip($file, $filename) {
        $abspath = dirname(Yii::app()->basePath) . '/';
        if ($zip_path = $abspath . dirname($file)) {

            $zip = new ZipArchive;
            if ($zip->open($zip_path . '/' . $filename . '.zip', ZipArchive::CREATE) === TRUE) {
                $file_name = 'mission_sentence.dat';
                if (file_exists($abspath . $file)) {
                    $zip->addFile($abspath . $file, $file_name);
                }
                if ($zip->close()) {
                    return true;
                } else {
                    return false;
                }
            } else {
                throw new CException('zip文件不能写入');
            }
        }
    }

    /**
     * 以utf8求取字符串长度
     * 
     * @param string $string     要计算的字符串编码
     * @return int
     */
    public static function strlenForUtf8($string) {
        $l = strlen($string);
        $p = $c = 0;
        while ($p < $l) {
            $a = $string[$p];
            if ($a < "\xC0")
                $p++;
            elseif ($a < "\xE0")
                $p += 2;
            elseif ($a < "\xF0")
                $p += 3;
            elseif ($a < "\xF8")
                $p += 4;
            elseif ($a < "\xFC")
                $p += 5;
            else
                $p += 6;
            $c++;
        }
        return $c;
    }

    /*
     * 获取ip
     * @return string
     */

    static public function getIp() {
        return Yii::app()->request->userHostAddress;
    }

    /*
     * 获取令牌
     * @return string
     */

    static function genToken($len = 32, $md5 = true) {
        # Seed random number generator
        # Only needed for PHP versions prior to 4.2
        mt_srand((double) microtime() * 1000000);
        # Array of characters, adjust as desired
        $chars = array(
            'Q', '@', '8', 'y', '%', '^', '5', 'Z', '(', 'G', '_', 'O', '`',
            'S', '-', 'N', '<', 'D', '{', '}', '[', ']', 'h', ';', 'W', '.',
            '/', '|', ':', '1', 'E', 'L', '4', '&', '6', '7', '#', '9', 'a',
            'A', 'b', 'B', '~', 'C', 'd', '>', 'e', '2', 'f', 'P', 'g', ')',
            '?', 'H', 'i', 'X', 'U', 'J', 'k', 'r', 'l', '3', 't', 'M', 'n',
            '=', 'o', '+', 'p', 'F', 'q', '!', 'K', 'R', 's', 'c', 'm', 'T',
            'v', 'j', 'u', 'V', 'w', ',', 'x', 'I', '$', 'Y', 'z', '*'
        );
        # Array indice friendly number of chars; 
        $numChars = count($chars) - 1;
        $token = '';
        # Create random token at the specified length
        for ($i = 0; $i < $len; $i++)
            $token .= $chars[mt_rand(0, $numChars)];

        # Should token be run through md5?

        if ($md5) {

            # Number of 32 char chunks
            $chunks = ceil(strlen($token) / 32);
            $md5token = '';

            # Run each chunk through md5

            for ($i = 1; $i <= $chunks; $i++)
                $md5token .= md5(substr($token, $i * 32 - 32, 32));

            # Trim the token

            $token = substr($md5token, 0, $len);
        } return $token;
    }
    /**
     * 转换用户id
     * @param unknown $username
     * @return unknown|number
     * 
     */
//    public static function getMemberId($username) {
//        if (is_numeric($username)) {
//            return ltrim($username, '0');
//        }
//        $username =mb_strtolower($username,'UTF-8');
//        $hash = hash('md5', $username);
//        $uid = '';
//        for ($i = 16; $i < 32; $i++) {
//            $uid .= decbin(ord($hash{$i}));
//        }
//        $uid = hash('crc32', $uid) . hash('crc32b', $uid);
//        return base_convert($uid, 16, 36);
//        //return  $uid + 0;
//    }
    
    
     /**
     * 转换用户id
     * @param unknown $username
     * @return unknown|number
     * 
     */
    public static function getMemberId($uid,$regtime) {
          $uid = (string) $uid; 
          $len = strlen($uid);
          $diff = 8- $len;
          return date('n',$regtime).strlen($uid).$uid.substr($regtime,-$diff,$diff ); 
        //return  $uid + 0;
    }


    static function newGenToken($username){
//         if (is_numeric($username)) {
//            return ltrim($username, '0');
//        }
        $username = mb_strtolower($username,'UTF-8');
        $hash = hash('md5', $username.CURRENT_TIME."9c6945559796648675a4d80bd1fd65ab");
        return $hash;
//        $uid = '';
//        for ($i = 0; $i < 32; $i++) {
//            $uid .= decbin(ord($hash{$i}));
//        }
//       $uid = hash('crc32', $uid) . hash('crc32b', $uid);
//        return base_convert($uid, 16, 10);
    } 

    /**
     * 页码转sql
     *
     * @param int $page 分页
     * @param int $perpage 每页显示数
     * @return array <1.start 2.limit>
     */
    public static function page2limit($page, $perpage = 10) {
        $limit = intval($perpage);
        $start = max(($page - 1) * $limit, 0);
        return array($start, $limit);
    }

    /**
     *  @desc 根据两点间的经纬度计算距离
     *  @param float $lat 纬度值
     *  @param float $lng 经度值
     */
    public static function getDistance($lat1, $lng1, $lat2, $lng2) {
        $earthRadius = 6367000; //approximate radius of earth in meters

        /*
          Convert these degrees to radians
          to work with the formula
         */

        $lat1 = ($lat1 * pi() ) / 180;
        $lng1 = ($lng1 * pi() ) / 180;

        $lat2 = ($lat2 * pi() ) / 180;
        $lng2 = ($lng2 * pi() ) / 180;

        /*
          Using the
          Haversine formula

          http://en.wikipedia.org/wiki/Haversine_formula

          calculate the distance
         */

        $calcLongitude = $lng2 - $lng1;
        $calcLatitude = $lat2 - $lat1;
        $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
        $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
        $calculatedDistance = $earthRadius * $stepTwo;

        return $calculatedDistance;
    }

    /**
     * 获取随机字符串
     *
     * @param int $length 字符串长度
     * @return string
     */
    public static function randstr($length) {
        return substr(md5(self::num_rand($length)), mt_rand(0, 32 - $length), $length);
    }

    /**
     * 获得随机数字符串
     *
     * @param int $length
     *        	随机数的长度
     * @return string 随机获得的字串
     */
    public static function generateRandStr($length) {
        $mt_string = 'AzBy0CxDwEv1FuGtHs2IrJqK3pLoM4nNmOlP5kQjRi6ShTgU7fVeW8dXcY9bZa';
        $randstr = '';
        for ($i = 0; $i < $length; $i++) {
            $randstr .= $mt_string[mt_rand(0, 61)];
        }
        return $randstr;
    }

    /**
     * 获取随机数
     *
     * @param int $length 随机数字个数
     * @return string
     */
    public static function num_rand($length) {
        mt_srand((double) microtime() * 1000000);
        $randVal = mt_rand(1, 9);
        for ($i = 1; $i < $length; $i++) {
            $randVal .= mt_rand(0, 9);
        }
        return $randVal;
    }

    /*
     * 指定key转换数组
     */

    public static function pk2array($arr, $pk, $key = FALSE) {
        if (empty($arr)) {
            return array();
        }
        $newarr = array();
        if (!$key) {
            foreach ($arr as $k => $v) {
                $newarr[$v[$pk]] = $v;
            }
        } else {
            foreach ($arr as $k => $v) {
                $newarr[$v[$pk]] = $v[$key];
            }
        }
        unset($arr);
        return $newarr;
    }

    public static function guid() {
        if (function_exists('com_create_guid')) {
            return com_create_guid();
        } else {

            mt_srand((double) microtime() * 10000); //optional for php 4.2.0 and up.
            $charid = md5(uniqid(rand(), true));
            return $charid;
            $hyphen = chr(45); // "-"
            $uuid = //chr(123)// "{"
                    substr($charid, 0, 8) . $hyphen
                    . substr($charid, 8, 4) . $hyphen
                    . substr($charid, 12, 4) . $hyphen
                    . substr($charid, 16, 4) . $hyphen
                    . substr($charid, 20, 12);
            //. chr(125); // "}"
            return $uuid;
        }
    }

    /* 计算他人生日 */

    public static function fomatHisBirthday($year, $month, $day) {
        return $year && $month && $day ? sprintf("%04d-%02d-%02d", $year, $month, $day) : '';
    }

    /* 判断用户浏览器 */

    public static function judgeUserAgent() {
        if (isset($_SERVER['HTTP_DEVICETYPE'])) {
            $agent =  strtolower($_SERVER['HTTP_DEVICETYPE']);
            if($agent =='android'){
                 return "Android";
            }elseif($agent =='ios'){
                  return "iPhone";
            }
        } elseif (isset($_SERVER['HTTP_USER_AGENT'])) {
            $agent = strtolower($_SERVER['HTTP_USER_AGENT']);

            //分析数据
            $is_pc = (strpos($agent, 'windows nt')) ? true : false;
            $is_iphone = (strpos($agent, 'iphone')) ? true : false;
            $is_ipad = (strpos($agent, 'ipad')) ? true : false;
            $is_android = (strpos($agent, 'android')) ? true : false;

            //输出数据 
            if ($is_pc) {
                return "PC";
            }
            if ($is_iphone) {
                return "iPhone";
            }
            if ($is_ipad) {
                return "iPad";
            }
            if ($is_android) {
                return "Android";
            }
        }
    }

    public static function judgeUserVersion() {
        return isset($_SERVER['HTTP_APPVERSION']) ? $_SERVER['HTTP_APPVERSION'] : (isset($_GET['version']) ? $_GET['version'] : '');
    }

    public static function judgeUserChannel() {
        return isset($_SERVER['HTTP_UMENGCHANNEL']) ? $_SERVER['HTTP_UMENGCHANNEL'] : 'Unknow';
    }

    /**
     * 生成密码
     *
     * @param string $password 源密码
     * @param string $salt
     * @return string
     */
    public static function buildPassword($password, $salt) {
        return md5(md5($password) . $salt);
    }

    /**
     * emoji表情编码
     * @param string $text
     */
    public static function encodeEmoji($text) {
        $strEncode = '';
        $length = mb_strlen($text, 'utf-8');
        for ($i = 0; $i < $length; $i++) {
            $_tmpStr = mb_substr($text, $i, 1, 'utf-8');
            if (strlen($_tmpStr) >= 4) {
                $strEncode .= '[[EMOJI:' . rawurlencode($_tmpStr) . ']]';
            } else {
                $strEncode .= $_tmpStr;
            }
        }
        return $strEncode;
    }

    /**
     * emoji表情解码
     * @param string $text
     * @return string|mixed
     */
    public static function decodeEmoji($text) {
        $text = preg_replace_callback("/\[\[EMOJI:(.*?)\]\]/", function($matches) {
            return rawurldecode($matches[1]);
        }, $text);
        return $text;
    }

    public static function build_order_no() {
        return date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
    }

    /**
     * Http Get/Post函数,请求为json格式
     * @param $url
     * @param $data
     * @param string $method
     * @return mixed
     */
    public static function Api_Request($url, $data, $method = "GET") {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        //以下两行，忽略https证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $method = strtoupper($method);
        if ($method == "POST") {
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        $content = curl_exec($ch);
        curl_close($ch);
        return $content;
    }
    
    /**
     * 获取小尺寸用户头像
     * @param string $avatar_path
     * @return number|unknown
     */
    public static function getSmallAvatar($avatar_path){
        if(strpos($avatar_path, '_')){
            $avatar_arr = explode('_', $avatar_path);
            $small_avatar = $avatar_arr[0].'_small_'.$avatar_arr[1];
            return is_file($small_avatar) ? $small_avatar : $avatar_path;
        }else return $avatar_path;
    }
    
    /**
     * 获取中尺寸用户头像
     * @param string $avatar_path
     * @return number|unknown
     */
    public static function getMiddleAvatar($avatar_path){
        if(strpos($avatar_path, '_')){
            $avatar_arr = explode('_', $avatar_path);
            $small_avatar = $avatar_arr[0].'_middle_'.$avatar_arr[1];
            return is_file($small_avatar) ? $small_avatar : $avatar_path;
        }else return $avatar_path;
    }

}
